package models;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import play.data.validation.Required;
import play.data.validation.Valid;
import play.db.jpa.Blob;
import play.db.jpa.Model;
import utils.CustomInFuture;

/**
 * The deal entity class. Contains attributes describing a deal (e.g. title, description, prices, and dates).
 * A deal is associated with an address, a district, a category, and a user (owner).
 * 
 */
@Entity
public class Deal extends Model {

	@Required(message = "validation.deal.title")
	public String title;

	@Required(message = "validation.deal.description")
	@Column(name = "description", length = 512)
	public String description;

	@Required(message = "validation.deal.oldPrice")
	@Column(precision = 6, scale = 2)
	public BigDecimal oldPrice;

	@Required(message = "validation.deal.discountPrice")
	@Column(precision = 6, scale = 2)
	public BigDecimal discountPrice;

	@Required(message = "validation.deal.startDate")
	@Temporal(TemporalType.DATE)
	@CustomInFuture
	public Date startDate;

	@Required(message = "validation.deal.endDate")
	@Temporal(TemporalType.DATE)
	@CustomInFuture
	public Date endDate;

	@Column(precision = 6, scale = 2)
	public double latitude;

	@Column(precision = 6, scale = 2)
	public double longitude;
	
	@Column
	public Blob photo;

	@Required
	@Valid
	@ManyToOne(cascade = CascadeType.ALL, targetEntity = Address.class)
	public Address address;

	@ManyToOne
	public Category category;

	@ManyToOne(fetch = FetchType.LAZY)
	public User user;

	@ManyToOne
	public District district;

	public Deal(String title, String description, BigDecimal oldPrice,
			BigDecimal discountPrice, Date startDate, Date endDate,
			Address address, Category category, User user, District district) {
		this.title = title;
		this.description = description;
		this.oldPrice = oldPrice;
		this.discountPrice = discountPrice;
		this.startDate = startDate;
		this.endDate = endDate;
		this.address = address;
		this.category = category;
		this.user = user;
		this.district = district;
	}

	public Deal() {}
	
	public String remainingDays() {
		Date timeOfEnd = this.endDate == null ? (new Date()) : this.endDate;
		long distance = timeOfEnd.getTime() - (new Date()).getTime();
		; 
		return distance > 0 ? Integer.valueOf(Long.valueOf(TimeUnit.MILLISECONDS.toDays(distance)).intValue()).toString() : "-";    
	}

}
